<template>
    <PopList :title="'样式编辑器'" :showButton="true" @ok="ok">
        <div class="model_style_box_content">
            <div class="model_content_top">
                <div class="model_style_textarea">
                    <textarea v-model="styleContent"></textarea>
                </div>
                <div class="model_style_footer">
                    <a href="https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/Styling"
                        target="_blank">style语言说明</a>
                    <button @click="saveStyle">另存为新样式</button>
                    <button @click="useStyle">应用</button>
                </div>
            </div>

        </div>
        <div class="images_bottom_content">
            <div class="images_img_list">
                <div v-for="(item, index) in styleList" class="images_img_lilist">
                    <div class="images_imgposition" :class="{ 'images_checkedactive': checkedactive == index }"
                        @click="changeStyle(item, index)" @contextmenu.prevent.stop="Message.warning('默认样式禁止修改')">
                        <img :src="item.thumbnail" alt="">
                        <span v-show="iconIsShow == index ? true : false">{{ item.name }}</span>
                    </div>
                    <div class="images_onlineimageName" @mouseenter="iconIsShow = index"
                        @mouseleave="iconIsShow = null">
                        {{ item.name }}
                    </div>
                </div>
                <div v-for="(item, index) in localStorageStyle" class="images_img_lilist">
                    <div class="images_imgposition" :class="{ 'images_checkedactive': checkedactive == index + 5 }"
                        @click="changeStyle(item, index + 5)" @contextmenu.prevent.stop="contexMenuEvent(item, index)">
                        <img :src="item.thumbnail" alt="">
                        <span v-show="iconIsShow == index ? true : false">{{ item.name }}</span>
                    </div>
                    <div class="images_onlineimageName" @mouseenter="iconIsShow = index" @mouseleave="iconIsShow = null"
                        v-if="inputIndex !== index">
                        {{ item.name }}
                    </div>
                    <input class="model_content_right_input" type="text" v-model="inputValue" v-else
                        @blur="changeName(item, index)" @keydown.enter="changeName(item, index)" :key="index"
                        ref="myInput">
                </div>
            </div>
        </div>
    </PopList>
    <ContextMenuCom :baseItems="menuContent"></ContextMenuCom>
</template>
<script setup lang="ts">
import { Message, messageBox } from "earthsdk-ui";
import { ES3DTileset } from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
import { inject, onBeforeUnmount, onMounted, ref } from 'vue';
import { SceneTree } from 'xbsj-xe2/dist-node/xe2';
import PopList from "../../../components/PopList.vue";
import ContextMenuCom from '../../../components/commom/ContextMenuCom.vue';
import { XbsjEarthUi } from "../../../scripts/xbsjEarthUi";
const xbsjEarthUi = inject('xbsjEarthUi') as XbsjEarthUi
const sceneTree = inject('sceneTree') as SceneTree
type menuContentType = {
    text: string;
    keys: string;
    func: () => void;
} | {
    type: "divider",
}
const menuContent = ref<Array<menuContentType>>([])
const props = withDefaults(defineProps<{
    defaultStyle: string
}>(), {
});
const { defaultStyle } = props
const styleList = ref([
    {
        name: "默认样式",
        code: "var style={}",
        thumbnail: "",

    },
    {
        name: "纯色",
        code: "var style = {\r\n    color: \"vec4(1,0,0,1)\"\r\n}",
        thumbnail: "",

    },
    {
        name: "半透明",
        code: "var style = {\r\n    color: \"vec4(1,1,1,0.5)\"\r\n}",
        thumbnail: "",

    },
    {
        name: "分类全透",
        code: "var style = {\r\n    color: \"vec4(0,0,1,0.01)\"\r\n}",
        thumbnail: "",

    },
    {
        name: "分类浅色",
        code: "var style = {\r\n    color: \"vec4(0,0,1,0.1)\"\r\n}",
        thumbnail: "",

    }
])
const localStorageStyle = ref()
const styleContent = ref()
const checkedactive = ref()
const iconIsShow = ref()
const inputIndex = ref()
const inputValue = ref()
const contextmenuItem = ref()
const myInput = ref<HTMLElement>();
const flag = ref(false)
const emits = defineEmits(['close']);
//失去焦点,按键enter
const changeName = (item: any, index: number) => {
    const modelStyle = window.localStorage.getItem('modelStyle')
    if (modelStyle) {
        const a = JSON.parse(modelStyle)
        a[index].name = inputValue.value
        window.localStorage.setItem('modelStyle', JSON.stringify(a))
        localStorageStyle.value = a
    }
    inputIndex.value = null
}
const contexMenuEvent = (item: any, index: number) => {//元素右键
    contextmenuItem.value = item
    if (!item) return
    const baseItems: Array<menuContentType> = [
        {
            text: "重命名",
            keys: "",
            func: () => {
                inputIndex.value = index
                inputValue.value = item.name
            },
        },
        {
            text: "更新缩略图",
            keys: "",
            func: () => {
                messageBox({ text: '确认更新缩略图吗？' })
                    .then(() => {
                        updateConfirm(index)
                    })
                    .catch((err) => {
                    })
            },
        },
        {
            text: "删除",
            keys: "",
            func: () => {
                messageBox({ text: '确认删除？' })
                    .then(() => {
                        deleteConfirm(index)
                    })
                    .catch((err) => {
                    })
            },
        }
    ];
    menuContent.value = baseItems
}
const close = () => {
    // const lastSelectedItem = sceneTree.lastSelectedItem
    // if (!lastSelectedItem) return
    // if (lastSelectedItem.type === 'ES3DTileset') {
    //     const sceneObject = lastSelectedItem.sceneObject as ES3DTileset
    //     if (styleTransformJson(defaultStyle)) {
    //         sceneObject.czmStyleJson = styleTransformJson(defaultStyle)
    //     } else {
    //         sceneObject.czmStyleJson = styleTransformJson('var style={}')
    //     }
    // }
    emits("close")
}
//删除
const deleteConfirm = (index: number) => {
    const modelStyle = window.localStorage.getItem('modelStyle')
    if (modelStyle) {
        let a = JSON.parse(modelStyle)
        a.splice(index, 1)
        window.localStorage.setItem('modelStyle', JSON.stringify(a))
        localStorageStyle.value = a
    }
    inputIndex.value = null
}

//更新缩略图
const updateConfirm = (index: number) => {
    const viewer = xbsjEarthUi.activeViewer
    if (!viewer) return
    viewer.capture().then(res => {
        if (res) {
            const modelStyle = window.localStorage.getItem('modelStyle')
            if (modelStyle) {
                const a = JSON.parse(modelStyle)
                a[index].thumbnail = res
                window.localStorage.setItem('modelStyle', JSON.stringify(a))
                localStorageStyle.value = a
            }
            inputIndex.value = null
        }
    }).catch(error => {
        console.log(error);

    })
}
//样式转换成json
const styleTransformJson = (str: string) => {
    if (!str) return
    const f = new Function(`${str}; return style;`)
    return f()
}
const ok = () => {
    flag.value = true
    if (!styleContent.value) {
        Message.error('样式未定义');
    }
    const lastSelectedItem = sceneTree.lastSelectedItem
    if (!lastSelectedItem) return
    if (lastSelectedItem.type === 'ES3DTileset') {
        const sceneObject = lastSelectedItem.sceneObject as ES3DTileset
        if (styleContent.value === '{}') {
            sceneObject.czmStyleJson = styleTransformJson('var style={}')
        } else if (styleTransformJson(styleContent.value)) {
            sceneObject.czmStyleJson = styleTransformJson(styleContent.value)
        }
    }
    emits("close", styleContent.value)
}
//另存为新样式
const saveStyle = () => {
    if (!styleContent.value) {
        Message.error('请输入内容之后在保存')
        return
    }
    const viewer = xbsjEarthUi.activeViewer
    if (!viewer) return
    viewer.capture().then(res => {
        if (res) {
            const parms = {
                name: '新建样式',
                code: styleContent.value,
                thumbnail: res
            }
            const modelStyle = window.localStorage.getItem('modelStyle')
            if (modelStyle) {
                const a = JSON.parse(modelStyle)
                a.push(parms)
                window.localStorage.setItem('modelStyle', JSON.stringify(a))
            } else {
                window.localStorage.setItem('modelStyle', JSON.stringify([parms]))
            }
            Message.success('另存样式成功')
            updateList()
        }
    }).catch(error => {
        console.log(error);
        Message.error(`另存样式成功!error:${error}`)
    })
}
const useStyle = () => {
    if (!styleContent.value) {
        Message.error('样式未定义');
    }
    const lastSelectedItem = sceneTree.lastSelectedItem
    if (!lastSelectedItem) return
    if (lastSelectedItem.type === 'ES3DTileset') {
        const sceneObject = lastSelectedItem.sceneObject as ES3DTileset
        if (styleTransformJson(styleContent.value)) {
            sceneObject.czmStyleJson = styleTransformJson(styleContent.value)
        }
    }
}
const changeStyle = (item: any, index: any) => {
    checkedactive.value = index
    styleContent.value = item.code
}
const updateList = () => {
    const modelStyle = window.localStorage.getItem('modelStyle')
    if (modelStyle) {
        const a = JSON.parse(modelStyle)
        localStorageStyle.value = a
    }
}
onMounted(() => {
    updateList()

})
onBeforeUnmount(() => {
    if (!flag.value) {
        close()
    }
})
</script>
